import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'dart:developer' as developer;
import 'dart:io';
import 'package:image_picker/image_picker.dart';
import '../../../common/routers/names.dart';
import '../../../common/services/user_service.dart';
import '../../../common/services/rongcloud_service.dart'; // 🔥 导入融云服务
import '../../../common/services/notification_service.dart'; // 🔥 导入通知服务
import '../../../common/services/notification_manager.dart'; // 🔥 导入通知管理器
import '../../../common/utils/smart_notification_util.dart'; // 🔥 导入智能通知工具
import '../../../common/models/index.dart';
import '../../../common/api/friend_api.dart';
import '../../../common/api/user_api.dart';
import '../../../common/utils/toast_util.dart';

class MyIndexController extends GetxController {
  MyIndexController();

  // 获取UserService实例
  UserService get userService => UserService.to;

  // 好友数量（实际显示为"粉丝数"）
  final RxInt _friendCount = 0.obs;
  int get friendCount => _friendCount.value;
  
  // 📝 新增：活动申请通知状态管理（参考MyApplication2的Config.ifInputActivity）
  final RxBool _hasActivityApplication = false.obs;
  bool get hasActivityApplication => _hasActivityApplication.value;
  
  // 📝 新增：爱好选中状态管理（与MyApplication2保持一致）
  final RxMap<String, bool> _selectedHobbies = <String, bool>{
    '吃': false,
    '喝': false, 
    '玩': false,
    '乐': false,
    '购': false,
  }.obs;
  
  Map<String, bool> get selectedHobbies => _selectedHobbies;
  
  /// 获取已选中的爱好列表
  List<String> get selectedHobbiesList => _selectedHobbies.entries
      .where((entry) => entry.value)
      .map((entry) => entry.key)
      .toList();

  _initData() async {
    // 打印详细的用户信息用于调试
    _printDetailedUserInfo();
    
    // 🔥 强制刷新用户信息，确保获取最新的粉丝数和点赞数
    developer.log('🔄 开始刷新用户信息以获取最新数据...');
    final refreshSuccess = await userService.refreshUserInfo();
    if (refreshSuccess) {
      developer.log('✅ 用户信息刷新成功，重新打印数据');
      _printDetailedUserInfo();
    } else {
      developer.log('❌ 用户信息刷新失败，使用本地缓存数据');
    }
    
    // 🔥 获取好友列表数量（用于显示“粉丝数”）
    await _loadFriendCount();
    
    // 📝 新增：初始化爱好选中状态
    await _initHobbiesState();
    
    // 📝 新增：加载活动申请通知状态
    _loadActivityApplicationStatus();
    
    update(["my_index"]);
  }

  /// 获取好友列表数量
  /// 按照MyApplication2项目的逻辑，"粉丝数"实际显示的是好友数量
  Future<void> _loadFriendCount() async {
    try {
      developer.log('🔄 =============== 开始获取好友列表数量 ===============');
      
      final userId = userService.currentUser?.userid;
      if (userId == null) {
        developer.log('❌ 用户ID为空，无法获取好友列表');
        return;
      }
      
      developer.log('👤 当前用户ID: $userId');
      
      // 调用好友列表API
      final friendListResponse = await FriendApi.getFriendList(
        userId: userId,
      );
      
      if (friendListResponse.isSuccess) {
        final friendCount = friendListResponse.count;
        _friendCount.value = friendCount;
        
        developer.log('✅ 好友列表获取成功');
        developer.log('👥 好友数量: $friendCount');
        developer.log('📝 好友列表详情:');
        for (final friend in friendListResponse.data) {
          developer.log('   👤 ${friend.username} (ID: ${friend.friendId})');
        }
        
        // 🔥 按照MyApplication2逻辑，将好友数量作为"粉丝数"显示
        developer.log('📊 UI将显示"粉丝数": $friendCount (实际为好友数量)');
        
      } else {
        developer.log('❌ 好友列表获取失败: ${friendListResponse.message}');
        _friendCount.value = 0;
      }
      
      developer.log('🔍 =============== 好友列表数量获取结束 ===============');
    } catch (e) {
      developer.log('💥 获取好友列表数量异常: $e');
      _friendCount.value = 0;
    }
  }

  /// 打印详细的用户信息用于调试
  void _printDetailedUserInfo() {
    try {
      final user = userService.currentUser;
      developer.log('🔍 ================ 详细用户信息调试 ================');
      
      if (user == null) {
        developer.log('❌ 用户信息为null');
        return;
      }
      
      developer.log('✅ 用户基本信息:');
      developer.log('  📱 用户ID: ${user.userid}');
      developer.log('  👤 用户名: ${user.username}');
      developer.log('  📞 手机号: ${user.userPhone}');
      developer.log('  🎂 年龄: ${user.userAge}');
      developer.log('  ⚥ 性别: ${user.userGender}');
      developer.log('  ✍️ 签名: ${user.userSignature}');
      developer.log('  🏷️ 标签原始数据: ${user.userTags} (类型: ${user.userTags.runtimeType})');
      developer.log('  ❤️ 点赞数: ${user.userLikes}');
      developer.log('  👥 粉丝数: ${user.userFollowers}');
      developer.log('  💰 积分: ${user.userPoints}');
      developer.log('  🎯 爱好原始数据: ${user.userHobbies} (类型: ${user.userHobbies.runtimeType})');
      developer.log('  🏙️ 城市: ${user.userCity}');
      developer.log('  📍 常出没地: ${user.userFrequentPlaces}');
      developer.log('  🎂 生日: ${user.userBirthday}');
      developer.log('  🆙 等级: ${user.userLevel}');
      developer.log('  🖼️ 头像URL: ${user.userAvatarUrl}');
      
      developer.log('📸 相册信息:');
      developer.log('  🖼️ 相册原始数据: ${user.userImgUrls} (类型: ${user.userImgUrls.runtimeType})');
      if (user.userImgUrls != null) {
        developer.log('  📊 相册图片数量: ${user.userImgUrls!.length}');
        for (int i = 0; i < user.userImgUrls!.length; i++) {
          developer.log('    🔗 图片$i: ${user.userImgUrls![i]}');
        }
      }
      
      developer.log('🔐 额外数据信息:');
      developer.log('  📦 extraData原始数据: ${user.extraData} (类型: ${user.extraData.runtimeType})');
      
      if (user.extraData != null) {
        developer.log('  🔑 extraData keys: ${user.extraData!.keys.toList()}');
        
        // 检查实名认证信息
        final realNameAuth = user.extraData!['realNameAuth'];
        developer.log('  🆔 realNameAuth数据: $realNameAuth (类型: ${realNameAuth.runtimeType})');
        
        if (realNameAuth != null) {
          developer.log('  ✅ 实名认证详细信息:');
          if (realNameAuth is Map) {
            for (var key in realNameAuth.keys) {
              developer.log('    📝 $key: ${realNameAuth[key]}');
            }
          }
        }
        
        // 检查融云信息
        final token = user.extraData!['token'];
        final rongUserId = user.extraData!['rongcloud_user_id'];
        developer.log('  💬 融云Token: ${token != null ? '已设置' : '未设置'}');
        developer.log('  👤 融云用户ID: $rongUserId');
      }
      
      developer.log('🔍 ================ 调试信息结束 ================');
    } catch (e) {
      developer.log('💥 打印用户信息时发生异常: $e');
    }
  }

  void onTap() {}

  // 🎯 根据积分计算等级（按照新的积分等级规定）
  int calculateLevelFromPoints(int points) {
    if (points >= 1200) {
      return 4; // 一言九鼎
    } else if (points >= 600) {
      return 3; // 真神
    } else if (points >= 300) {
      return 2; // 创造者
    } else if (points >= 100) {
      return 1; // 守护者
    } else {
      return 0; // 追随者
    }
  }
  
  // 🎯 根据积分返回等级名称
  String getLevelNameFromPoints(int points) {
    final level = calculateLevelFromPoints(points);
    switch (level) {
      case 0:
        return '追随者';
      case 1:
        return '守护者';
      case 2:
        return '创造者';
      case 3:
        return '真神';
      case 4:
        return '一言九鼎';
      default:
        return '追随者';
    }
  }

  // 刷新用户信息
  Future<void> refreshUserInfo() async {
    try {
      developer.log('开始刷新用户信息');
      final success = await userService.refreshUserInfo();
      if (success) {
        developer.log('✅ 用户信息刷新成功');
        // 同时刷新好友数量
        await _loadFriendCount();
        update(["my_index"]);
      } else {
        developer.log('❌ 用户信息刷新失败');
      }
    } catch (e) {
      developer.log('💥 刷新用户信息异常: $e');
    }
  }

  /// 刷新好友数量
  /// 公开方法，可在需要时手动刷新好友数量
  Future<void> refreshFriendCount() async {
    await _loadFriendCount();
    update(["my_index"]);
  }

  // 🔥 新增：显示退出登录确认对话框（参考MyApplication2的dialogLoginOut）
  Future<void> showLogoutConfirmDialog() async {
    try {
      developer.log('📋 显示退出登录确认对话框');
      
      final bool? confirmed = await Get.dialog<bool>(
        AlertDialog(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(16),
          ),
          title: Row(
            children: [
              Icon(
                Icons.logout,
                color: Color(0xFFD46A6A),
                size: 28,
              ),
              SizedBox(width: 12),
              Text(
                '退出登录',
                style: TextStyle(
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                  color: Colors.black87,
                ),
              ),
            ],
          ),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                '确定要退出当前账号吗？',
                style: TextStyle(
                  fontSize: 16,
                  color: Colors.black87,
                ),
              ),
              SizedBox(height: 8),
              Text(
                '退出后需要重新登录才能使用',
                style: TextStyle(
                  fontSize: 14,
                  color: Colors.grey[600],
                ),
              ),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () => Get.back(result: false),
              style: TextButton.styleFrom(
                foregroundColor: Colors.grey[600],
                padding: EdgeInsets.symmetric(horizontal: 20, vertical: 12),
              ),
              child: Text(
                '取消',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ),
            ElevatedButton(
              onPressed: () => Get.back(result: true),
              style: ElevatedButton.styleFrom(
                backgroundColor: Color(0xFFD46A6A),
                foregroundColor: Colors.white,
                padding: EdgeInsets.symmetric(horizontal: 20, vertical: 12),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8),
                ),
              ),
              child: Text(
                '退出',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w600,
                ),
              ),
            ),
          ],
        ),
        barrierDismissible: true,
      );
      
      if (confirmed == true) {
        developer.log('✅ 用户确认退出登录');
        await logout();
      } else {
        developer.log('❌ 用户取消退出登录');
      }
      
    } catch (e) {
      developer.log('💥 显示退出登录对话框异常: $e');
    }
  }

  // 退出登录 - 增强版本，参考MyApplication2的完整退出流程
  Future<void> logout() async {
    try {
      developer.log('🚀 =============== 开始完整退出登录操作 ===============');
      
      // 获取当前用户信息用于日志
      final userService = UserService.to;
      final userName = userService.userName;
      
      developer.log('📤 退出用户: $userName');
      
      // 🔥 1. 断开融云连接并清理融云相关数据（参考MyApplication2的RongCoreClient.getInstance().logout()）
      try {
        if (Get.isRegistered<RongCloudService>()) {
          final rongCloudService = RongCloudService.to;
          await rongCloudService.logoutAndClearAll();
          developer.log('✅ 融云服务清理完成');
        }
      } catch (e) {
        developer.log('⚠️ 融云服务清理异常: $e');
      }
      
      // 🔥 2. 清理通知相关状态和缓存
      try {
        // 清理智能通知系统
        if (Get.isRegistered<SmartNotificationUtil>()) {
          final smartNotification = SmartNotificationUtil.instance;
          await smartNotification.clearAllNotifications();
          developer.log('✅ 智能通知系统清理完成');
        }
        
        // 清理通知管理器状态
        if (Get.isRegistered<NotificationManager>()) {
          final notificationManager = NotificationManager.to;
          notificationManager.clearFriendRequestNotification();
          developer.log('✅ 通知管理器清理完成');
        }
        
        // 清理本地通知服务
        if (Get.isRegistered<NotificationService>()) {
          final notificationService = NotificationService.to;
          await notificationService.clearAllNotifications();
          developer.log('✅ 本地通知服务清理完成');
        }
      } catch (e) {
        developer.log('⚠️ 通知系统清理异常: $e');
      }
      
      // 🔥 3. 清除用户信息和本地存储（参考MyApplication2的SPUtils.clear()）
      userService.clearUser();
      developer.log('✅ 用户信息和本地存储清理完成');
      
      // 🔥 4. 清理当前页面的状态
      _hasActivityApplication.value = false;
      _selectedHobbies.updateAll((key, value) => false);
      _friendCount.value = 0;
      developer.log('✅ 页面状态清理完成');
      
      developer.log('📊 退出后状态检查:');
      developer.log('  🔐 登录状态: ${userService.isLoggedIn}');
      developer.log('  👤 用户信息: ${userService.currentUser == null ? "已清除" : "仍存在"}');
      
      // 🔥 5. 返回登录页面（参考MyApplication2的openActivity(LoginActivity.class)）
      Get.offAllNamed(RouteNames.systemLogin);
      
      developer.log('🎉 =============== 完整退出登录成功 ===============');
      
    } catch (e) {
      developer.log('💥 ❌ 退出登录异常: $e');
      
      // 🔥 即使出现异常也要执行最基本的清理并返回登录页面
      try {
        UserService.to.clearUser();
      } catch (clearError) {
        developer.log('💥 强制清理用户信息异常: $clearError');
      }
      
      Get.offAllNamed(RouteNames.systemLogin);
      developer.log('🔄 异常情况下已强制跳转到登录页面');
    }
  }

  /// 更新用户昵称
  Future<void> updateUserName(String newUserName) async {
    if (newUserName.trim().isEmpty) {
      developer.log('❌ 昵称不能为空');
      return;
    }

    final success = await userService.updateUserInfoToServer(username: newUserName.trim());
    if (success) {
      developer.log('✅ 昵称更新成功: $newUserName');
    }
  }

  /// 更新用户签名
  Future<void> updateUserSignature(String newSignature) async {
    final success = await userService.updateUserInfoToServer(userSignature: newSignature.trim());
    if (success) {
      developer.log('✅ 签名更新成功: $newSignature');
    }
  }

  /// 更新用户性别
  Future<void> updateUserGender(String newGender) async {
    final success = await userService.updateUserInfoToServer(userGender: newGender);
    if (success) {
      developer.log('✅ 性别更新成功: $newGender');
    }
  }

  /// 更新用户常出没地
  Future<void> updateUserFrequentPlaces(String newPlaces) async {
    final success = await userService.updateUserInfoToServer(userFrequentPlaces: newPlaces.trim());
    if (success) {
      developer.log('✅ 常出没地更新成功: $newPlaces');
    }
  }

  /// 更新用户生日（📝 修改：与MyApplication2保持一致，使用生日而非年龄）
  Future<void> updateUserBirthday(String newBirthday) async {
    final success = await userService.updateUserInfoToServer(userBirthday: newBirthday);
    if (success) {
      developer.log('✅ 生日更新成功: $newBirthday');
    }
  }
  
  /// 更新用户头像（📝 新增：与MyApplication2保持一致）
  Future<void> updateUserAvatar(String newAvatarUrl) async {
    final success = await userService.updateUserInfoToServer(userAvatarUrl: newAvatarUrl);
    if (success) {
      developer.log('✅ 头像更新成功: $newAvatarUrl');
    }
  }
  
  /// 更新用户相册（📝 新增：与MyApplication2保持一致）
  Future<void> updateUserAlbum(List<String> newImgUrls) async {
    final success = await userService.updateUserInfoToServer(userImgUrls: newImgUrls);
    if (success) {
      developer.log('✅ 相册更新成功: ${newImgUrls.length}张图片');
    }
  }
  
  /// 📝 新增：初始化爱好选中状态（与MyApplication2保持一致）
  Future<void> _initHobbiesState() async {
    try {
      developer.log('🍽️ 开始初始化爱好选中状态...');
      
      // 从用户信息中获取爱好数据
      final userHobbies = userService.currentUser?.userHobbies;
      
      if (userHobbies != null && userHobbies.isNotEmpty) {
        developer.log('📝 用户已有爱好数据: $userHobbies');
        
        // 重置所有爱好为未选中
        _selectedHobbies.updateAll((key, value) => false);
        
        // 根据用户数据设置选中状态
        for (final hobby in userHobbies) {
          if (_selectedHobbies.containsKey(hobby)) {
            _selectedHobbies[hobby] = true;
            developer.log('✅ 设置爱好 "$hobby" 为选中状态');
          }
        }
      } else {
        developer.log('📝 用户暂无爱好数据，使用默认状态（全部未选中）');
        // 默认全部未选中
        _selectedHobbies.updateAll((key, value) => false);
      }
      
      developer.log('🍽️ 爱好状态初始化完成: ${_selectedHobbies.toString()}');
      
    } catch (e) {
      developer.log('💥 初始化爱好状态异常: $e');
      // 异常情况下重置为全部未选中
      _selectedHobbies.updateAll((key, value) => false);
    }
  }
  
  /// 📝 新增：切换爱好选中状态（与MyApplication2保持一致）
  void toggleHobby(String hobby) {
    if (_selectedHobbies.containsKey(hobby)) {
      final currentState = _selectedHobbies[hobby] ?? false;
      _selectedHobbies[hobby] = !currentState;
      
      developer.log('🔄 切换爱好 "$hobby" 状态: $currentState -> ${!currentState}');
      developer.log('📝 当前选中的爱好: $selectedHobbiesList');
      
      // 🔥 修复：立即保存爱好设置到服务器，避免在完成按钮时重复请求
      _saveHobbiesToServerSilently();
      
      // 更新UI
      update(["my_index"]);
    } else {
      developer.log('❌ 无效的爱好选项: $hobby');
    }
  }
  
  /// 📝 新增：静默保存爱好到服务器（避免重复弹出提示）
  Future<void> _saveHobbiesToServerSilently() async {
    try {
      developer.log('🍽️ 静默保存爱好到服务器...');
      developer.log('📝 将要提交的爱好: $selectedHobbiesList');
      
      // 只提交选中的爱好，与MyApplication2保持一致
      final success = await userService.updateUserInfoToServer(
        userHobbies: selectedHobbiesList,
        userImgUrls: userService.currentUser?.userImgUrls, // 保持现有相册
      );
      
      if (success) {
        developer.log('✅ 爱好静默保存成功');
      } else {
        developer.log('❌ 爱好静默保存失败');
      }
    } catch (e) {
      developer.log('💥 静默保存爱好异常: $e');
    }
  }
  
  /// 📝 新增：更新用户爱好到服务器（与MyApplication2保持一致）
  Future<void> updateUserHobbies() async {
    try {
      developer.log('🍽️ 开始更新用户爱好到服务器...');
      developer.log('📝 将要提交的爱好: $selectedHobbiesList');
      
      // 🔥 只提交选中的爱好，与MyApplication2保持一致
      final success = await userService.updateUserInfoToServer(
        userHobbies: selectedHobbiesList, // 🔥 传递用户选择的爱好
        userImgUrls: userService.currentUser?.userImgUrls, // 保持现有相册
      );
      
      if (success) {
        developer.log('✅ 爱好更新成功');
        ToastUtil.success('爱好设置已保存');
      } else {
        developer.log('❌ 爱好更新失败');
        ToastUtil.error('爱好设置保存失败');
      }
    } catch (e) {
      developer.log('💥 更新爱好异常: $e');
      ToastUtil.error('更新爱好时发生错误');
    }
  }

  /// 图片选择器实例
  final ImagePicker _picker = ImagePicker();
  
  /// 上传进度状态
  final RxDouble _uploadProgress = 0.0.obs;
  double get uploadProgress => _uploadProgress.value;
  
  /// 是否正在上传
  final RxBool _isUploading = false.obs;
  bool get isUploading => _isUploading.value;
  
  /// 🔥 新增：相册上传状态
  final RxBool _isUploadingAlbum = false.obs;
  bool get isUploadingAlbum => _isUploadingAlbum.value;
  
  final RxDouble _albumUploadProgress = 0.0.obs;
  double get albumUploadProgress => _albumUploadProgress.value;

  /// 选择并上传头像
  Future<void> pickAndUploadAvatar() async {
    try {
      developer.log('开始选择头像');
      
      // 显示选择对话框，针对iOS模拟器只提供相册选择
      final ImageSource? source = await _showImageSourceDialog();
      if (source == null) {
        developer.log('用户取消选择');
        return;
      }

      // iOS模拟器的相机可能不可用，如果选择相机但失败，自动降级到相册
      ImageSource finalSource = source;
      
      try {
        // 选择图片
        final XFile? image = await _picker.pickImage(
          source: finalSource,
          maxWidth: 800, // 限制图片尺寸以减少上传大小
          maxHeight: 800,
          imageQuality: 85, // 压缩质量
        );

        if (image == null) {
          developer.log('未选择图片');
          return;
        }

        developer.log('已选择图片: ${image.path}');
        
        // 开始上传
        _isUploading.value = true;
        _uploadProgress.value = 0.0;

        final success = await userService.uploadUserAvatar(
          imagePath: image.path,
          onProgress: (sent, total) {
            _uploadProgress.value = sent / total;
            developer.log('上传进度: ${(_uploadProgress.value * 100).toStringAsFixed(1)}%');
          },
        );

        _isUploading.value = false;

        if (success) {
          developer.log('✅ 头像上传成功');
          // 强制刷新界面，确保新头像显示
          update(["my_index"]);
          developer.log('🔄 界面已刷新，显示新头像');
        } else {
          developer.log('❌ 头像上传失败，请重试');
        }
      } catch (pickError) {
        developer.log('图片选择错误: $pickError');
        
        // 如果是iOS模拟器且选择的是相机，尝试降级到相册
        if (finalSource == ImageSource.camera && pickError.toString().contains('channel-error')) {
          developer.log('iOS模拟器相机不可用，尝试使用相册');
          developer.log('提示: iOS模拟器相机不可用，请从相册选择图片');
          
          // 重新尝试相册选择
          try {
            final XFile? image = await _picker.pickImage(
              source: ImageSource.gallery,
              maxWidth: 800,
              maxHeight: 800,
              imageQuality: 85,
            );

            if (image != null) {
              developer.log('从相册选择成功: ${image.path}');
              
              _isUploading.value = true;
              _uploadProgress.value = 0.0;

              final success = await userService.uploadUserAvatar(
                imagePath: image.path,
                onProgress: (sent, total) {
                  _uploadProgress.value = sent / total;
                  developer.log('上传进度: ${(_uploadProgress.value * 100).toStringAsFixed(1)}%');
                },
              );

              _isUploading.value = false;

              if (success) {
                developer.log('✅ 头像上传成功');
                // 强制刷新界面，确保新头像显示
                update(["my_index"]);
                developer.log('🔄 界面已刷新，显示新头像');
              }
            }
          } catch (galleryError) {
            developer.log('相册选择也失败: $galleryError');
            _isUploading.value = false;
            developer.log('错误: iOS模拟器图片选择功能受限，请在真机上测试');
          }
        } else {
          _isUploading.value = false;
          throw pickError; // 其他错误继续抛出
        }
      }
    } catch (e) {
      developer.log('💥 选择上传头像异常: $e');
      _isUploading.value = false;
      
      String errorMessage = '头像上传出错';
      if (e.toString().contains('channel-error')) {
        errorMessage = 'iOS模拟器功能受限，建议在真机上测试';
      } else if (e.toString().contains('PlatformException')) {
        errorMessage = '设备功能受限，请检查权限设置';
      }
      
      developer.log('提示: $errorMessage');
    }
  }

  /// 实名认证状态
  final RxBool _isSubmittingAuth = false.obs;
  bool get isSubmittingAuth => _isSubmittingAuth.value;

  /// 当前认证状态
  final Rx<RealnameAuthResponse?> _authStatus = Rx<RealnameAuthResponse?>(null);
  RealnameAuthResponse? get authStatus => _authStatus.value;

  /// 提交实名认证
  Future<bool> submitRealnameAuth({
    required String realName,
    required String idCardNo,
  }) async {
    if (realName.trim().isEmpty) {
      developer.log('❌ 实名认证提交失败: 请输入真实姓名');
      ToastUtil.error('请输入真实姓名');  // 🔥 修复：添加用户提示，与MyApplication2保持一致
      return false;
    }

    if (idCardNo.trim().isEmpty) {
      developer.log('❌ 实名认证提交失败: 请输入身份证号码');
      ToastUtil.error('请输入身份证号码');  // 🔥 修复：添加用户提示，与MyApplication2保持一致
      return false;
    }

    // 简单的身份证号格式验证
    if (!_isValidIdCard(idCardNo.trim())) {
      developer.log('❌ 实名认证提交失败: 请输入正确的身份证号码格式');
      ToastUtil.error('请输入正确的身份证号码格式');  // 🔥 修复：添加用户提示
      return false;
    }

    try {
      _isSubmittingAuth.value = true;
      developer.log('开始提交实名认证');

      final response = await userService.submitRealnameAuth(
        realName: realName.trim(),
        idCardNo: idCardNo.trim(),
      );

      _authStatus.value = response;

      if (response.isSuccess) {
        developer.log('✅ 实名认证提交成功');
        developer.log('实名认证信息已提交，当前状态：${response.authStatusDescription}');
        developer.log('脱敏身份证: ${response.maskedIdCard}');
        developer.log('认证时间: ${response.authTime}');
        developer.log('是否已认证: ${response.isVerified}');
        
        // 🔥 修复：添加成功提示，与MyApplication2保持一致
        ToastUtil.success(response.message.isNotEmpty ? response.message : '实名认证信息已提交');
        
        // 🔥 修复：如果认证成功，刷新用户信息和界面状态
        if (response.isVerified) {
          developer.log('🎉 实名认证已通过，刷新界面状态');
          // 重新查询认证状态，确保界面状态同步
          await checkAuthStatus();
          // 刷新用户信息
          await refreshUserInfo();
          // 强制更新界面
          update();
        } else {
          developer.log('📝 实名认证已提交，等待审核');
          // 即使未通过，也要更新认证状态
          await checkAuthStatus();
          update();
        }
        
        return true;
      } else {
        developer.log('❌ 实名认证提交失败: ${response.message}');
        ToastUtil.error(response.message.isNotEmpty ? response.message : '实名认证提交失败');  // 🔥 修复：添加失败提示
        return false;
      }
    } catch (e) {
      developer.log('💥 提交实名认证异常: $e');
      developer.log('认证提交出现异常，请重试');
      ToastUtil.error('认证提交出现异常，请重试');  // 🔥 修复：添加异常提示，与MyApplication2保持一致
      return false;
    } finally {
      _isSubmittingAuth.value = false;
    }
  }

  /// 查询实名认证状态
  Future<void> checkAuthStatus() async {
    try {
      developer.log('开始查询实名认证状态');
      
      // 先检查本地用户信息中是否有认证数据
      final realNameAuth = userService.currentUser?.extraData?['realNameAuth'];
      if (realNameAuth != null) {
        developer.log('📍 从本地用户信息获取认证状态: $realNameAuth');
        
        // 从本地数据构建认证状态响应
        final authResponse = RealnameAuthResponse(
          status: 'success',
          message: realNameAuth['message'] ?? '认证信息已获取',
          data: RealnameAuthData(
            userid: userService.currentUser?.userid ?? 0,
            authStatus: realNameAuth['status'] ?? 0,
            statusMsg: realNameAuth['message'] ?? '',
            verified: realNameAuth['verified'] ?? false,
            flowId: realNameAuth['flowId'] ?? '',
            authTime: realNameAuth['authTime'] ?? '',
            idCardNo: realNameAuth['idCardNo'] ?? '',
          ),
        );
        
        _authStatus.value = authResponse;
        developer.log('✅ 从本地获取认证状态成功: ${authResponse.authStatusDescription}');
        developer.log('📝 认证姓名: ${realNameAuth['name']}');
        developer.log('🆔 脱敏身份证: ${realNameAuth['idCardNo']}');
        developer.log('⏰ 认证时间: ${realNameAuth['authTime']}');
        developer.log('✔️ 认证状态: ${realNameAuth['verified'] == true ? '已认证' : '未认证'}');
        return;
      }
      
      // 如果本地没有，再从服务器查询
      developer.log('本地无认证信息，从服务器查询...');
      final response = await userService.checkRealnameAuthStatus();
      _authStatus.value = response;

      if (response.isSuccess) {
        developer.log('✅ 服务器认证状态查询成功: ${response.authStatusDescription}');
      } else {
        developer.log('❌ 服务器认证状态查询失败: ${response.message}');
      }
    } catch (e) {
      developer.log('💥 查询认证状态异常: $e');
    }
  }

  /// 验证身份证号格式
  bool _isValidIdCard(String idCard) {
    // 简单的身份证号验证：18位数字，或17位数字+X
    final RegExp idCardRegex = RegExp(r'^\d{17}[\dXx]$');
    return idCardRegex.hasMatch(idCard);
  }

  /// 显示图片来源选择对话框
  Future<ImageSource?> _showImageSourceDialog() async {
    // 根据平台显示不同的提示
    String cameraSubtitle = '';
    String gallerySubtitle = '';
    
    if (kIsWeb) {
      cameraSubtitle = 'Web平台不支持';
      gallerySubtitle = '推荐选择';
    } else if (Platform.isIOS) {
      if (kDebugMode) {
        cameraSubtitle = 'iOS模拟器可能不支持';
        gallerySubtitle = '推荐选择';
      } else {
        cameraSubtitle = '拍摄新照片';
        gallerySubtitle = '从相册选择';
      }
    } else if (Platform.isAndroid) {
      cameraSubtitle = '拍摄新照片';
      gallerySubtitle = '从相册选择';
    }
    
    ImageSource? selectedSource;
    
    await Get.bottomSheet(
      Container(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
        ),
        child: SafeArea(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // 顶部标题
              Container(
                padding: EdgeInsets.symmetric(vertical: 20),
                child: Column(
                  children: [
                    // 小横条装饰
                    Container(
                      width: 40,
                      height: 4,
                      decoration: BoxDecoration(
                        color: Colors.grey[300],
                        borderRadius: BorderRadius.circular(2),
                      ),
                    ),
                    SizedBox(height: 16),
                    Text(
                      '选择图片来源',
                      style: TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                        color: Colors.black87,
                      ),
                    ),
                  ],
                ),
              ),
              
              // 选项列表
              Padding(
                padding: EdgeInsets.symmetric(horizontal: 20),
                child: Column(
                  children: [
                    // 拍照选项
                    GestureDetector(
                      onTap: () {
                        selectedSource = ImageSource.camera;
                        Get.back();
                      },
                      child: Container(
                        width: double.infinity,
                        padding: EdgeInsets.symmetric(vertical: 16),
                        decoration: BoxDecoration(
                          color: Colors.grey[50],
                          borderRadius: BorderRadius.circular(12),
                          border: Border.all(color: Colors.grey[200]!),
                        ),
                        child: Row(
                          children: [
                            SizedBox(width: 16),
                            Container(
                              padding: EdgeInsets.all(10),
                              decoration: BoxDecoration(
                                color: Color(0xFFD46A6A).withOpacity(0.1),
                                borderRadius: BorderRadius.circular(10),
                              ),
                              child: Icon(
                                Icons.camera_alt,
                                color: Color(0xFFD46A6A),
                                size: 24,
                              ),
                            ),
                            SizedBox(width: 16),
                            Expanded(
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(
                                    '拍照',
                                    style: TextStyle(
                                      fontSize: 16,
                                      fontWeight: FontWeight.w500,
                                      color: Colors.black87,
                                    ),
                                  ),
                                  if (cameraSubtitle.isNotEmpty) ...[
                                    SizedBox(height: 4),
                                    Text(
                                      cameraSubtitle,
                                      style: TextStyle(
                                        fontSize: 13,
                                        color: cameraSubtitle.contains('不支持') || cameraSubtitle.contains('可能不支持')
                                            ? Colors.orange[600]
                                            : Colors.blue[600],
                                      ),
                                    ),
                                  ],
                                ],
                              ),
                            ),
                            Icon(
                              Icons.chevron_right,
                              color: Colors.grey[400],
                              size: 20,
                            ),
                            SizedBox(width: 16),
                          ],
                        ),
                      ),
                    ),
                    
                    SizedBox(height: 12),
                    
                    // 从相册选择选项
                    GestureDetector(
                      onTap: () {
                        selectedSource = ImageSource.gallery;
                        Get.back();
                      },
                      child: Container(
                        width: double.infinity,
                        padding: EdgeInsets.symmetric(vertical: 16),
                        decoration: BoxDecoration(
                          color: Colors.grey[50],
                          borderRadius: BorderRadius.circular(12),
                          border: Border.all(color: Colors.grey[200]!),
                        ),
                        child: Row(
                          children: [
                            SizedBox(width: 16),
                            Container(
                              padding: EdgeInsets.all(10),
                              decoration: BoxDecoration(
                                color: Color(0xFFD46A6A).withOpacity(0.1),
                                borderRadius: BorderRadius.circular(10),
                              ),
                              child: Icon(
                                Icons.photo_library,
                                color: Color(0xFFD46A6A),
                                size: 24,
                              ),
                            ),
                            SizedBox(width: 16),
                            Expanded(
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(
                                    '从相册选择',
                                    style: TextStyle(
                                      fontSize: 16,
                                      fontWeight: FontWeight.w500,
                                      color: Colors.black87,
                                    ),
                                  ),
                                  if (gallerySubtitle.isNotEmpty) ...[
                                    SizedBox(height: 4),
                                    Text(
                                      gallerySubtitle,
                                      style: TextStyle(
                                        fontSize: 13,
                                        color: gallerySubtitle.contains('推荐')
                                            ? Colors.green[600]
                                            : Colors.blue[600],
                                      ),
                                    ),
                                  ],
                                ],
                              ),
                            ),
                            Icon(
                              Icons.chevron_right,
                              color: Colors.grey[400],
                              size: 20,
                            ),
                            SizedBox(width: 16),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              
              // 取消按钮
              Padding(
                padding: EdgeInsets.all(20),
                child: SizedBox(
                  width: double.infinity,
                  height: 48,
                  child: ElevatedButton(
                    onPressed: () => Get.back(),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.grey[200],
                      foregroundColor: Colors.black87,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(12),
                      ),
                      elevation: 0,
                    ),
                    child: Text(
                      '取消',
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
      isScrollControlled: true,
    );
    
    return selectedSource;
  }

  // ================== 相册管理功能 ==================
  
  /// 选择并添加相册图片
  Future<void> pickAndAddAlbumImage() async {
    try {
      developer.log('开始选择相册图片');
      
      // 📝 相册限制：最多4张图片
      final currentImages = userService.currentUser?.userImgUrls ?? [];
      const maxImages = 4; // 限制为最多4张图片
      if (currentImages.length >= maxImages) {
        developer.log('相册图片已达到最大数量：$maxImages张');
        ToastUtil.info('相册最多只能添加${maxImages}张图片');
        return;
      }
      
      // 显示选择对话框
      final ImageSource? source = await _showImageSourceDialog();
      if (source == null) {
        developer.log('用户取消选择');
        return;
      }

      try {
        // 选择图片
        final XFile? image = await _picker.pickImage(
          source: source,
          maxWidth: 800,
          maxHeight: 800,
          imageQuality: 85,
        );

        if (image == null) {
          developer.log('未选择图片');
          return;
        }

        developer.log('已选择相册图片: ${image.path}');
        
        // 开始上传
        _isUploading.value = true;
        _uploadProgress.value = 0.0;

        final success = await userService.uploadAlbumImage(
          imagePath: image.path,
          onProgress: (sent, total) {
            _uploadProgress.value = sent / total;
            developer.log('相册图片上传进度: ${(_uploadProgress.value * 100).toStringAsFixed(1)}%');
          },
        );

        _isUploading.value = false;

        if (success) {
          developer.log('✅ 相册图片上传成功');
          ToastUtil.success( '图片上传成功');
          // 刷新界面
          update(["my_index"]);
          developer.log('🔄 相册界面已刷新');
        } else {
          developer.log('❌ 相册图片上传失败');
          ToastUtil.error( '图片上传失败，请重试');
        }
      } catch (pickError) {
        // iOS模拟器相机不可用的处理逻辑（与头像上传相同）
        if (source == ImageSource.camera && pickError.toString().contains('channel-error')) {
          developer.log('iOS模拟器相机不可用，尝试使用相册');
          ToastUtil.info( 'iOS模拟器相机不可用，请从相册选择图片');
          
          try {
            final XFile? image = await _picker.pickImage(
              source: ImageSource.gallery,
              maxWidth: 800,
              maxHeight: 800,
              imageQuality: 85,
            );

            if (image != null) {
              developer.log('从相册选择相册图片成功: ${image.path}');
              
              _isUploading.value = true;
              _uploadProgress.value = 0.0;

              final success = await userService.uploadAlbumImage(
                imagePath: image.path,
                onProgress: (sent, total) {
                  _uploadProgress.value = sent / total;
                  developer.log('相册图片上传进度: ${(_uploadProgress.value * 100).toStringAsFixed(1)}%');
                },
              );

              _isUploading.value = false;

              if (success) {
                developer.log('✅ 相册图片上传成功');
                ToastUtil.success( '图片上传成功');
                update(["my_index"]);
                developer.log('🔄 相册界面已刷新');
              }
            }
          } catch (galleryError) {
            developer.log('相册选择也失败: $galleryError');
            _isUploading.value = false;
            ToastUtil.error( 'iOS模拟器图片选择功能受限，请在真机上测试');
          }
        } else {
          _isUploading.value = false;
          developer.log('图片选择失败: $pickError');
          ToastUtil.error( '图片选择失败，请重试');
        }
      }
    } catch (e) {
      _isUploading.value = false;
      developer.log('❌ 添加相册图片异常: $e');
      ToastUtil.error( '添加图片失败: $e');
    }
  }
  
  /// 删除相册图片
  Future<void> deleteAlbumImage(int index) async {
    try {
      developer.log('开始删除相册图片，索引: $index');
      
      final currentImages = userService.currentUser?.userImgUrls ?? [];
      if (index < 0 || index >= currentImages.length) {
        developer.log('无效的图片索引: $index');
        ToastUtil.error( '无效的图片索引');
        return;
      }
      
      // 显示确认对话框
      final bool? confirmed = await Get.dialog<bool>(
        AlertDialog(
          title: Text('确认删除'),
          content: Text('确定要删除这张图片吗？'),
          actions: [
            TextButton(
              child: Text('取消'),
              onPressed: () => Get.back(result: false),
            ),
            TextButton(
              child: Text('删除', style: TextStyle(color: Colors.red)),
              onPressed: () => Get.back(result: true),
            ),
          ],
        ),
      );
      
      if (confirmed != true) {
        developer.log('用户取消删除');
        return;
      }
      
      final success = await userService.removeAlbumImage(index);
      if (success) {
        developer.log('✅ 相册图片删除成功');
        ToastUtil.success( '图片删除成功');
        // 刷新界面
        update(["my_index"]);
        developer.log('🔄 相册界面已刷新');
      } else {
        developer.log('❌ 相册图片删除失败');
        ToastUtil.error( '图片删除失败，请重试');
      }
    } catch (e) {
      developer.log('❌ 删除相册图片异常: $e');
      ToastUtil.error( '删除图片失败: $e');
    }
  }
  
  /// 替换相册图片
  Future<void> replaceAlbumImage(int index) async {
    try {
      developer.log('开始替换相册图片，索引: $index');
      
      final currentImages = userService.currentUser?.userImgUrls ?? [];
      if (index < 0 || index >= currentImages.length) {
        developer.log('无效的图片索引: $index');
        ToastUtil.error( '无效的图片索引');
        return;
      }
      
      // 显示选择对话框
      final ImageSource? source = await _showImageSourceDialog();
      if (source == null) {
        developer.log('用户取消选择');
        return;
      }

      try {
        // 选择图片
        final XFile? image = await _picker.pickImage(
          source: source,
          maxWidth: 800,
          maxHeight: 800,
          imageQuality: 85,
        );

        if (image == null) {
          developer.log('未选择图片');
          return;
        }

        developer.log('已选择替换图片: ${image.path}');
        
        // 开始上传并替换
        _isUploading.value = true;
        _uploadProgress.value = 0.0;

        final success = await userService.replaceAlbumImage(
          index: index,
          imagePath: image.path,
          onProgress: (sent, total) {
            _uploadProgress.value = sent / total;
            developer.log('替换图片上传进度: ${(_uploadProgress.value * 100).toStringAsFixed(1)}%');
          },
        );

        _isUploading.value = false;

        if (success) {
          developer.log('✅ 相册图片替换成功');
          ToastUtil.success( '图片替换成功');
          // 刷新界面
          update(["my_index"]);
          developer.log('🔄 相册界面已刷新');
        } else {
          developer.log('❌ 相册图片替换失败');
          ToastUtil.error( '图片替换失败，请重试');
        }
      } catch (pickError) {
        // iOS模拟器相机不可用的处理逻辑
        if (source == ImageSource.camera && pickError.toString().contains('channel-error')) {
          developer.log('iOS模拟器相机不可用，尝试使用相册');
          ToastUtil.info( 'iOS模拟器相机不可用，请从相册选择图片');
          
          try {
            final XFile? image = await _picker.pickImage(
              source: ImageSource.gallery,
              maxWidth: 800,
              maxHeight: 800,
              imageQuality: 85,
            );

            if (image != null) {
              developer.log('从相册选择替换图片成功: ${image.path}');
              
              _isUploading.value = true;
              _uploadProgress.value = 0.0;

              final success = await userService.replaceAlbumImage(
                index: index,
                imagePath: image.path,
                onProgress: (sent, total) {
                  _uploadProgress.value = sent / total;
                  developer.log('替换图片上传进度: ${(_uploadProgress.value * 100).toStringAsFixed(1)}%');
                },
              );

              _isUploading.value = false;

              if (success) {
                developer.log('✅ 相册图片替换成功');
                ToastUtil.success( '图片替换成功');
                update(["my_index"]);
                developer.log('🔄 相册界面已刷新');
              }
            }
          } catch (galleryError) {
            developer.log('相册选择也失败: $galleryError');
            _isUploading.value = false;
            ToastUtil.error( 'iOS模拟器图片选择功能受限，请在真机上测试');
          }
        } else {
          _isUploading.value = false;
          developer.log('图片选择失败: $pickError');
          ToastUtil.error( '图片选择失败，请重试');
        }
      }
    } catch (e) {
      _isUploading.value = false;
      developer.log('❌ 替换相册图片异常: $e');
      ToastUtil.error( '替换图片失败: $e');
    }
  }



  /// 🔥 新增：从相机拍照并上传到相册（与MyApplication2保持一致）
  Future<void> pickAndUploadAlbumImageFromCamera() async {
    try {
      developer.log('📷 开始从相机拍照添加到相册');
      
      final XFile? pickedFile = await _picker.pickImage(
        source: ImageSource.camera,
        maxWidth: 1024,
        maxHeight: 1024,
        imageQuality: 80,
      );
      
      if (pickedFile != null) {
        await _uploadAlbumImage(pickedFile.path);
      } else {
        developer.log('❌ 用户取消了拍照');
      }
    } catch (e) {
      developer.log('💥 拍照异常: $e');
      ToastUtil.error( '拍照失败：$e');
    }
  }
  
  /// 🔥 新增：从相册选择并上传到相册（与MyApplication2保持一致）
  Future<void> pickAndUploadAlbumImageFromGallery() async {
    try {
      developer.log('🖼️ 开始从相册选择添加到相册');
      
      final XFile? pickedFile = await _picker.pickImage(
        source: ImageSource.gallery,
        maxWidth: 1024,
        maxHeight: 1024,
        imageQuality: 80,
      );
      
      if (pickedFile != null) {
        await _uploadAlbumImage(pickedFile.path);
      } else {
        developer.log('❌ 用户取消了选择');
      }
    } catch (e) {
      developer.log('💥 选择图片异常: $e');
      ToastUtil.error( '选择图片失败：$e');
    }
  }
  
  /// 🔥 新增：上传相册图片的内部方法
  Future<void> _uploadAlbumImage(String imagePath) async {
    try {
      developer.log('📷 开始上传相册图片: $imagePath');
      
      _isUploadingAlbum.value = true;
      _albumUploadProgress.value = 0.0;
      
      final userId = userService.currentUser?.userid;
      if (userId == null) {
        throw Exception('用户ID为空，无法上传图片');
      }
      
      // 上传图片到服务器
      final uploadResponse = await UserApi.uploadUserImage(
        userId: userId,
        filePath: imagePath,
        onProgress: (sent, total) {
          _albumUploadProgress.value = sent / total;
        },
      );
      
      if (uploadResponse.isSuccess && uploadResponse.imageUrl != null) {
        developer.log('✅ 图片上传成功: ${uploadResponse.imageUrl}');
        
        // 获取当前相册图片列表
        final currentImages = List<String>.from(userService.currentUser?.userImgUrls ?? []);
        
        // 添加新图片到列表末尾
        currentImages.add(uploadResponse.imageUrl!);
        
        // 更新到服务器
        final success = await userService.updateUserInfoToServer(userImgUrls: currentImages);
        if (success) {
          developer.log('✅ 相册更新成功，当前图片数量: ${currentImages.length}');
          ToastUtil.success('照片已添加到相册');
          update(["my_index"]); // 刷新UI
        } else {
          developer.log('❌ 相册更新失败');
          ToastUtil.error('相册更新失败');
        }
      } else {
        developer.log('❌ 图片上传失败: ${uploadResponse.message}');
        ToastUtil.error('图片上传失败');
      }
    } catch (e) {
      developer.log('💥 上传相册图片异常: $e');
      ToastUtil.error('上传图片失败');
    } finally {
      _isUploadingAlbum.value = false;
      _albumUploadProgress.value = 0.0;
    }
  }

  /// 📝 新增：设置活动申请通知状态（参考MyApplication2的Logic）
  void setActivityApplicationNotification(bool hasNotification) {
    _hasActivityApplication.value = hasNotification;
    
    // 保存到本地存储（使用GetStorage，与其他设置保持一致）
    final storage = GetStorage();
    storage.write('ifInputActivity', hasNotification ? '1' : '0');
    
    developer.log('🎯 活动申请通知状态更新: $hasNotification');
    update(["my_index"]); // 更新UI
  }
  
  /// 📝 新增：清除活动申请通知状态
  void clearActivityApplicationNotification() {
    setActivityApplicationNotification(false);
    developer.log('✅ 活动申请通知状态已清除');
  }
  
  /// 📝 新增：从本地存储加载活动申请状态
  void _loadActivityApplicationStatus() {
    try {
      final storage = GetStorage();
      final status = storage.read('ifInputActivity') ?? '0';
      _hasActivityApplication.value = status == '1';
      
      developer.log('📋 从本地加载活动申请通知状态: ${_hasActivityApplication.value}');
    } catch (e) {
      developer.log('💥 加载活动申请状态异常: $e');
      _hasActivityApplication.value = false;
    }
  }

  // 在页面准备好时调用
  @override
  void onReady() {
    super.onReady();
    _initData();
  }

  // @override
  // void onClose() {
  //   super.onClose();
  // }
}
